<template>
  <div>
    <h3>同步和异步写法</h3>
    <el-form ref='form' :model='formModel' :rules='rules'>
      <el-form-item label='年龄' prop='age'>
        <el-input v-model='formModel.age'></el-input>
      </el-form-item>
      <el-button type='primary' @click='asyncSubmit'>同步调用</el-button> {{asyncResult}}
      <el-button type='primary' @click='syncSubmit'>异步调用</el-button> {{syncResult}}

    </el-form>
  </div>
</template>

<script>
export default {
  name: 'async-sync',
  data () {
    return {
      rules: {
        age: [
          {
            required: true, message: '年龄必填', trigger: ['change', 'blur']
          }
        ]
      },
      formModel: {
        age: null
      },
      asyncResult: '',
      syncResult: ''
    }
  },
  methods: {
    asyncSubmit () {
      // 方式一： 传入回调函数， 此处为同步调用
      this.$refs['form'].validate((valid, failFields) => {
        if (!valid) {
          // 校验不通过， failFields --> [字段1， 字段2] 失败的数组
          console.log('校验不通过的字段', failFields)
          this.asyncResult = false
          return
        }

        this.asyncResult = true
      })
    },
    async syncSubmit () {
      // 方式二： 异步调用
      try {
        const res = await this.$refs['form'].validate()

        console.log(res)
        this.syncResult = true
      } catch (e) {
        this.syncResult = false
        // 校验不通过, 这里的e 就是 第一种方式中回调函数的valid字段， 这里是不会返回失败的 failFields字段的
      }
    }
  }

}
</script>
